/* 
 * Enterprise Library Extensions - DI + ORM.
 * Copyright (C) 2006
 *
 * GNU General Public License
 *
 * This program is free software; you can redistribute 
 * it and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 */
using System;
using System.Collections;
using System.Collections.Specialized;
using ELE.EnterpriseLibrary.Naming;
using ELE.Common.Util;
using ELE.EnterpriseLibrary.Common.Logging;

namespace ELE.EnterpriseLibrary.Naming.Spi
{
	/// <summary>
  /// This class contains methods for creating context objects and objects referred to by location information in the naming or directory service. 
  /// <br/><br/>This class cannot be instantiated. It has only static methods. 
  /// <br/><br/>The mention of URL in the documentation for this class refers to a URL string as defined by RFC 1738 and its related RFCs. It is any string that conforms to the syntax described therein, and may not always have corresponding support in the java.net.URL class or Web browsers. 
  /// <br/><br/>NamingManager is safe for concurrent access by multiple threads. 
  /// <br/><br/>Except as otherwise noted, a Name or environment parameter passed to any method is owned by the caller. The implementation will not modify the object or keep a reference to it, although it may keep a reference to a clone or copy. 
	/// </summary>
	public class NamingManager
	{
    private static IObjectFactoryBuilder sBuilder;
    private static IInitialContextFactoryBuilder sInitCtxBuilder;
    /// <summary>
    /// Constant that holds the name of the environment property into which GetContinuationContext() stores the value of its CannotProceedException parameter. This property is inherited by the continuation context, and may be used by that context's service provider to inspect the fields of the exception. 
    /// The value of this constant is "ELE.EnterpriseLibrary.Naming.Spi.CannotProceedException".
    /// </summary>
    public const string CPE = "ELE.EnterpriseLibrary.Naming.Spi.CannotProceedException";
    /// <summary>
    /// The ObjectFactoryBuilder determines the policy used when trying to load object factories. See getObjectInstance() and class ObjectFactory for a description of the default policy. setObjectFactoryBuilder() overrides this default policy by installing an ObjectFactoryBuilder. Subsequent object factories will be loaded and created using the installed builder. 
    /// The builder can only be installed if the executing thread is allowed (by the security manager's checkSetFactory() method) to do so. Once installed, the builder cannot be replaced. 
    /// </summary>
    /// <exception cref="NamingException">builder cannot be installed for a non-security-related reason.</exception>
    public static IObjectFactoryBuilder ObjectFactoryBuilder
    {
      set { sBuilder = value; }
    }
    /// <summary>
    /// Determines whether an initial context factory builder has been set.
    /// </summary>
    public static bool HasInitialContextFactoryBuilder
    {
      get { return sInitCtxBuilder != null;}
    }
    /// <summary>
    /// Sets the InitialContextFactory builder to be builder. 
    /// The builder can only be installed if the executing thread is allowed by the security manager to do so. 
    /// Once installed, the builder cannot be replaced
    /// </summary>
    public static IInitialContextFactoryBuilder InitialContextFactoryBuilder
    {
      set { sInitCtxBuilder = value; }
    }
    /// <summary>
    /// Creates an initial context using the specified environment properties. 
    /// <br/><br/>If an IInitialContextFactoryBuilder has been installed, it is used to create the factory for 
    /// creating the initial context. 
    /// Otherwise, the class specified in the NamingContextConstants.INITIAL_CONTEXT_FACTORY environment property is used. 
    /// Note that an initial context factory (an object that implements the IInitialContextFactory interface) 
    /// must be public and must have a public constructor that accepts no arguments.
    /// </summary>
    /// <param name="environment">The possibly null environment properties used when creating the context</param>
    /// <returns>A non-null initial context</returns>
    /// <exception cref="NoInitialContextException">
    /// If the NamingContextConstants.INITIAL_CONTEXT_FACTORY property is not found or names a nonexistent 
    /// class or a class that cannot be instantiated, or if the initial context could not be 
    /// created for some other reason.</exception>
    public static INamingContext GetInitialContext(Hashtable environment)
    {
      INamingContext initialContext = null;
      if(HasInitialContextFactoryBuilder)
      {
        IInitialContextFactory ctxFactory = sInitCtxBuilder.CreateInitialContextFactory(environment);
        initialContext = ctxFactory.GetInitialContext(environment);
      }
      else
      {
        if(environment.ContainsKey(NamingContextConstants.INITIAL_CONTEXT_FACTORY) && environment[NamingContextConstants.INITIAL_CONTEXT_FACTORY] != null)
        {
          string ctxFactoryClassName = null;
          string ctxFactoryAssemblyName = null;
          if(environment[NamingContextConstants.INITIAL_CONTEXT_FACTORY] is string)
          {
            ctxFactoryClassName = (string)environment[NamingContextConstants.INITIAL_CONTEXT_FACTORY];
          }
          else if(environment[NamingContextConstants.INITIAL_CONTEXT_FACTORY] is ClassAssemblyPair)
          {
            ClassAssemblyPair cap = (ClassAssemblyPair) environment[NamingContextConstants.INITIAL_CONTEXT_FACTORY];
            ctxFactoryClassName = cap.ClassAssemblyName;
          }
          else if(environment[NamingContextConstants.INITIAL_CONTEXT_FACTORY] is IReferenceable)
          {
            IReferenceable refer = (IReferenceable) environment[NamingContextConstants.INITIAL_CONTEXT_FACTORY];
            ctxFactoryClassName = refer.Reference.ClassFactory + "," + refer.Reference.ClassFactoryAssembly;
          }
          int firstCommaIndex = ctxFactoryClassName.IndexOf(",");
          if (firstCommaIndex > 0)
          {
            ctxFactoryAssemblyName = ctxFactoryClassName.Substring(firstCommaIndex + 1);
            ctxFactoryClassName = ctxFactoryClassName.Substring(0,firstCommaIndex);
          }
          else if (environment.ContainsKey(NamingContextConstants.INITIAL_CONTEXT_FACTORY_ASSEMBLY))
          {
            ctxFactoryAssemblyName = (string)environment[NamingContextConstants.INITIAL_CONTEXT_FACTORY_ASSEMBLY];
          }
          try
          {
            IInitialContextFactory ctxFactory = (IInitialContextFactory)ObjectFactory.CreateInstance(ctxFactoryAssemblyName, ctxFactoryClassName);
            initialContext = ctxFactory.GetInitialContext(environment);
          }
          catch(Exception e)
          {
            throw new NoInitialContextException(e.Message);
          }
        }
      }
      if(initialContext == null)
      {
        throw new NoInitialContextException("Factory failed to initialize context from NamingManager.GetInitialContext");
      }
      return initialContext;
    }

    // OBJECT CONSTRUCTION BELOW

    private static StringCollection sInProcessObjects;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="name"></param>
    /// <param name="ctx"></param>
    /// <returns></returns>
    protected static bool AddToInProcess(string name, INamingContext ctx)
    {
      //ctx.Log("NamingManager: Adding to in process object named " + name, null, ELE.EnterpriseLibrary.Logging.LogLevel.Debug);
      if (sInProcessObjects == null)
      {
        sInProcessObjects = new StringCollection();
      }
      bool isIn = true;
      if (sInProcessObjects.Contains(name))
      {
        ctx.Log("NamingManager: Object named " + name + " is already in list skipping circular reference", null, LogLevel.Warning);
        isIn = false;
      }
      else
      {
        sInProcessObjects.Add(name);
      }
      if(ctx is InitialContext)
      {
        isIn = ((InitialContext)ctx).AddToInProcess(name);
      }
      return isIn;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="name"></param>
    /// <param name="ctx">The context</param>
    protected static void RemoveFromInProcess(string name, INamingContext ctx)
    {
      //ctx.Log("NamingManager: Removing from in process object named " + name, null, ELE.EnterpriseLibrary.Logging.LogLevel.Debug);
      if (sInProcessObjects != null)
      {
        sInProcessObjects.Remove(name);
      }
    }
    /// <summary>
    /// Creates an instance of an object for the specified object and environment. 
    /// <br/><br/>If an object factory builder has been installed, it is used to create a factory for creating 
    /// the object. Otherwise, the following rules are used to create the object: 
    /// <br/>If refInfo is a Reference or Referenceable containing a factory class name, use the named factory 
    /// to create the object. Return refInfo if the factory cannot be created. 
    /// If an exception is encountered while creating the factory, it is passed up to the caller. 
    /// <br/><br/>If refInfo is a Reference or Referenceable with no factory class name, and the address or addresses are 
    /// StringRefAddrs with address type "URL", try the URL context factory corresponding to each URL's scheme id 
    /// to create the object (see GetURLContext()). If that fails, continue to the next step. 
    /// Use the object factories specified in the NamingContextConstants.OBJECT_FACTORIES property of the environment, 
    /// and of the provider resource file associated with nameCtx, in that order. The value of this property is a 
    /// colon-separated list of factory class names that are tried in order, and the first one that succeeds in 
    /// creating an object is the one used. 
    /// If none of the factories can be loaded, return refInfo. If an exception is encountered while creating the object, 
    /// the exception is passed up to the caller. 
    /// <br/><br/>Service providers that implement the IDirContext interface should use DirectoryManager.GetObjectInstance(), 
    /// not this method. Service providers that implement only the INamingContext interface should use this method. 
    /// <br/><br/>Note that an object factory (an object that implements the IObjectFactory interface) must be public and 
    /// must have a public constructor that accepts no arguments. 
    /// <br/><br/>The name and nameCtx parameters may optionally be used to specify the name of the object being created. 
    /// name is the name of the object, relative to context nameCtx. This information could be useful to the object 
    /// factory or to the object implementation. If there are several possible contexts from which the object could 
    /// be named -- as will often be the case -- it is up to the caller to select one. A good rule of thumb is to 
    /// select the "deepest" context available. If nameCtx is null, name is relative to the default initial context. 
    /// If no name is being specified, the name parameter should be null.
    /// </summary>
    /// <param name="refInfo">The possibly null object for which to create an object</param>
    /// <param name="name">The name of this object relative to nameCtx. Specifying a name is optional; if it is omitted, 
    /// name should be null.</param>
    /// <param name="nameCtx">The context relative to which the name parameter is specified. If null, name is relative 
    /// to the default initial context.</param>
    /// <param name="environment">The possibly null environment to be used in the creation of the object factory and 
    /// the object.</param>
    /// <returns>An object created using refInfo; or refInfo if an object cannot be created using the algorithm 
    /// described above.</returns>
    /// <exception cref="NamingException">if a naming exception was encountered while attempting to get a URL context, 
    /// or if one of the factories accessed throws a NamingException.</exception>
    /// <exception cref="Exception">if one of the factories accessed throws an exception, or if an error was encountered 
    /// while loading and instantiating the factory and object classes. A factory should only throw an exception if it 
    /// does not want other factories to be used in an attempt to create an object. 
    /// See IObjectFactory.GetObjectInstance</exception>
    public static object GetObjectInstance(object refInfo, IName name, INamingContext nameCtx, Hashtable environment)
    {
      object objectInstance = null;
      IObjectFactory objFactory = null;
      if(nameCtx == null)
      {
        nameCtx = GetInitialContext(environment);
      }
//      if (!AddToInProcess(name.ToString(), nameCtx))
//      {
//        nameCtx.Log("NamingManager: Cannot handle circular dependencies found for object named .. " + name.ToString(), null, ELE.EnterpriseLibrary.Logging.LogLevel.Warn);
//        
//        return objectInstance;
//      }
      try
      {
        if (sBuilder != null)
        {
          objFactory = sBuilder.CreateObjectFactory(refInfo, environment);
          objectInstance = objFactory.GetObjectInstance(refInfo, name, nameCtx, environment);
        }
        else if (refInfo is IReferenceable)
        {
          IReferenceable refer = (IReferenceable)refInfo;
          try
          {
            objFactory = (IObjectFactory)ObjectFactory.CreateInstance(refer.Reference.ClassFactoryAssembly, refer.Reference.ClassFactory);
            objectInstance = objFactory.GetObjectInstance(refInfo, name, nameCtx, environment);
          }
          catch(ResourceInitializationException rie)
          {
            throw rie;
          }
          catch (Exception e)
          { throw e; }
        }
        if (objectInstance == null && environment.ContainsKey(NamingContextConstants.OBJECT_FACTORIES))
        {
          object factoriesObj = environment[NamingContextConstants.OBJECT_FACTORIES];
          if (factoriesObj != null)
          {
            if (factoriesObj is ICollection)
            {
              ICollection factoriesCollection = (ICollection)factoriesObj;
              int indx = 0;
              foreach (object factoryObj in factoriesCollection)
              {
                if (factoryObj is ClassAssemblyPair)
                {
                  try
                  {
                    ClassAssemblyPair factory = (ClassAssemblyPair)factoryObj;
                    objFactory = (IObjectFactory)ObjectFactory.CreateInstance(factory.AssemblyName, factory.ClassName);
                    objectInstance = objFactory.GetObjectInstance(refInfo, name, nameCtx, environment);
                  }
                  catch(ResourceInitializationException rie)
                  {
                    throw rie;
                  }
                  catch (Exception e)
                  {
                    throw e;
                  }
                }
                else if (factoryObj is String)
                {
                  string factoryClass = (string)factoryObj;
                  string factoryAssembly = null;
                  if (environment.ContainsKey(NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES) &&
                    environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES] != null)
                  {
                    if (environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES] is String)
                    {
                      factoryAssembly = (string)environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES];
                    }
                    else if (environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES] is IList)
                    {
                      object faObj = ((IList)environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES])[indx];
                      if (faObj != null && faObj is string)
                      {
                        factoryAssembly = (string)faObj;
                      }
                    }
                  }
                  try
                  {
                    objFactory = (IObjectFactory)ObjectFactory.CreateInstance(factoryAssembly, factoryClass);
                    objectInstance = objFactory.GetObjectInstance(refInfo, name, nameCtx, environment);
                  }
                  catch(ResourceInitializationException rie)
                  {
                    throw rie;
                  }
                  catch { }

                }
                if (objectInstance != null)
                {
                  break;
                }
                indx++;
              }
            }
            else if (factoriesObj is ClassAssemblyPair)
            {
              try
              {
                ClassAssemblyPair factory = (ClassAssemblyPair)factoriesObj;
                objFactory = (IObjectFactory)ObjectFactory.CreateInstance(factory.AssemblyName, factory.ClassName);
                objectInstance = objFactory.GetObjectInstance(refInfo, name, nameCtx, environment);
              }
              catch(ResourceInitializationException rie)
              {
                throw rie;
              }
              catch { }
            }
            else if (factoriesObj is string)
            {
              string factoryClass = (string)factoriesObj;
              string factoryAssembly = null;
              if (environment.ContainsKey(NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES) &&
                environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES] != null)
              {
                if (environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES] is String)
                {
                  factoryAssembly = (string)environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES];
                }
                else if (environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES] is IList)
                {
                  IList col = (IList)environment[NamingContextConstants.OBJECT_FACTORY_ASSEMBLIES];
                  if (col.Count > 0)
                  {
                    object faObj = col[0];
                    if (faObj != null && faObj is string)
                    {
                      factoryAssembly = (string)faObj;
                    }
                  }
                }
              }
              try
              {
                objFactory = (IObjectFactory)ObjectFactory.CreateInstance(factoryAssembly, factoryClass);
                objectInstance = objFactory.GetObjectInstance(refInfo, name, nameCtx, environment);
              }
              catch(ResourceInitializationException rie)
              {
                throw rie;
              }
              catch { }
            }
            else if (factoriesObj is IReferenceable)
            {
              IReferenceable refer = (IReferenceable)factoriesObj;
              try
              {
                objFactory = (IObjectFactory)ObjectFactory.CreateInstance(refer.Reference.ClassFactoryAssembly, refer.Reference.ClassFactory);
                objectInstance = objFactory.GetObjectInstance(refInfo, name, nameCtx, environment);
              }
              catch(ResourceInitializationException rie)
              {
                throw rie;
              }
              catch (Exception e)
              { throw e; }
            }
          }

        }
      }
      catch(ResourceInitializationException resExcep)
      {
        throw resExcep;
      }
      catch (Exception exep)
      {
        nameCtx.Log("NamingManager: Error creating instance of object named " + name.ToString() + " No usuable factory found", exep, LogLevel.Error);
      }
      finally
      {
//        RemoveFromInProcess(name.ToString(), nameCtx);
      }
      if(objectInstance == null)
      {
        return refInfo;
      }
      return objectInstance;
    }
   // I am not sure about implementing the following methods from JNDI yet
    //public static Context GetContinuationContext(CannotProceedException cpe) throws NamingException
    //public static Context GetURLContext(String scheme, Hashtable environment) throws NamingException


	}
}
